package com.cooqe.basefinder;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cooqe.entity.ItMetric;
import com.cooqe.entity.ItResFind;
import com.cooqe.mapper.ItFinderMapper;
import com.cooqe.mapper.ItMetricMapper;
import com.cooqe.mapper.ItResFindMapper;
import com.cooqe.collection_snmp.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2023/11/14-2023
 * @Description: finder 基础类
 */
@SuppressWarnings("all")
public abstract class AbstractBaseFinder {

    @Autowired
    private ItFinderMapper itFinderMapper;
    @Autowired
    private ItResFindMapper itResFindMapper;
    @Autowired
    private ItMetricMapper itMetricMapper;

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    /**
     * xx-job 调度执行入口
     * params 是执行该 job 任务所需要的必须的参数
     * 比如：资源采集模版id
     */
    public void schedulingExecute(String params) {
        //获取模版参数 (ip、端口、用户、密码等信息)
        // inContainerName: snmpFinderJob、sshFinderJob、pingFinderJob
        String inContainerName = CommonUtil.getContainerSimpleName(this.getClass());
        QueryWrapper<ItResFind> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("finder_id", inContainerName);
        ItResFind itResFind = itResFindMapper.selectOne(queryWrapper);
        JSONObject templateParam = JSONObject.parseObject(itResFind.getParamsValue());

        //采集之前逻辑
        beforeCollection(templateParam);

        //获取采集指标、真正执行采集
        List<ItMetric> metricList = new ArrayList<>();
        doCollection(metricList);

        //清空 ThreadLocal中信息
        threadLocal.remove();
    }


    /**
     * 采集之前逻辑
     * 如建立 数据库连接池、建立session 会话等
     */
    public abstract void beforeCollection(JSONObject jsonObject);


    /**
     * 真正执行采集方法
     */
    public abstract void doCollection(List<ItMetric> metricList);

}